package com.ext.demomemcache.controller;

import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

@RestController
@Slf4j
public class testController {

    @Autowired
    private MemcachedClient client;

    @GetMapping("/get1")
    public String  getTest() throws InterruptedException {
        OperationFuture<Boolean> flag = client.set("name", 5000, "louis");
        // 取出缓存
        Object value = client.get("name");
        log.info(value.toString());
        // 多线程睡眠5秒,让
        Thread.sleep(5000);
        value = client.get("name");
        log.info(value.toString());
        System.out.println(value+"---------tom------");
        return "success";
    }

    /**
     * 实现分布式锁
     * @return
     */
    @GetMapping("/get2")
    public boolean get1(){
        String key="key1";
        Object obj="刘备";
        if (client.get(key) == null) {
            boolean bl = client.add(key, 5, obj).getStatus().isSuccess(); // exp 5 是5秒之后锁会自动解开
            if ( bl) {
                log.info("成功获得锁--------------");
                log.info(client.get("key1").toString());
                return true;
            }else{
                log.info("没有获得锁--------------");
                return false;
            }
        }
        log.info("没有获得锁--------------");
        return false;
    }

    @GetMapping("/get3")
    public String  get2(){
        Set<String> str = new TreeSet<String>();
        str.add("first");//添加元素
        str.add("second");
        str.add("third");
        str.add("first");//重复元素
        //遍历，通过迭代器
        Iterator<String> it = str.iterator();
        System.out.println("通过迭代器输出");
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        //通过foreach
        System.out.println("通过foreach输出");
        for(String s:str)
        {
            System.out.println(s);
        }
        return  "success";
    }


    @GetMapping("/get4")
    public String  get4(){
        Set<String> str = new HashSet<String>();
        str.add("first");//添加元素
        str.add("second");
        str.add("3");
        str.remove("first");//删除元素
        //遍历，通过迭代器
        Iterator<String> it = str.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        //通过foreach
        for(String s:str)
        {
            System.out.println(s);
        }
        return "seccess";
    }

}
